package com.aggregate.iot.sanstar.device.support;

import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.iot.sanstar.device.support.utils.JSON;
import com.aggregate.iot.sanstar.device.support.utils.MD5;
import com.aggregate.iot.sanstar.device.support.utils.SHA1;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 盛思达专属工具类
 * @author Moyq5
 * @date 2017年9月29日
 */
public class Tool {
	
	private static Logger log = LoggerFactory.getLogger(Tool.class);
	
	public static boolean verify(String jsonString, String key) {
		Map<String, Object> map = JSON.toObject(jsonString, new TypeReference<TreeMap<String, Object>>() {});
		return verify(map, key);
	}
	
	public static String sign(String jsonString, String key) {
		Map<String, Object> map = JSON.toObject(jsonString, new TypeReference<TreeMap<String, Object>>() {});
		return sign(map, key);
	}
	
	private static String sign(Map<String, Object> map, String key) {
		map.put("key", key);
		map.remove("sign");
		String queryString = toQueryString(map);
		log.debug("签名内容：{}", queryString);
		String sign = MD5.MD5Encode(SHA1.encrypt(queryString).toLowerCase());
		log.debug("签名值：{}", sign);
		return sign;
	}
	
	private static boolean verify(Map<String, Object> map, String key) {
		String paramSign = String.valueOf(map.get("sign"));
		String generSign = sign(map, key);
		return paramSign.equalsIgnoreCase(generSign);
	}
	
	private static String toQueryString(Map<String, Object> data) {
		StringBuffer sb = new StringBuffer();
		for(Map.Entry<String, Object> entry : data.entrySet()) {
			if (null != entry.getValue() && !String.valueOf(entry.getValue()).isEmpty()) {
				sb.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		if (data.size() > 0) {
			sb.delete(sb.length()-1, sb.length());// 去掉最后的“&”
		}
		log.debug("组装结果：{}", sb.toString());
		return sb.toString();
	}
	
}